<?php
namespace Core\Component\Crypt;
use \Phalcon\Mvc\User\Component;
/**
 * Crypt plugin.
 */
class Aes extends Component
{
    protected $_key = "1234567891111117";

    protected $_iv = "1234567891111117";

    public function __construct() {
        if(!extension_loaded("mcrypt")) {
            throw new Exception('Aes encrypt failed, mcrypt module not loaded!');
        }
        if (!$this->_key) {
            throw new Exception('Aes encrypt failed, key not found!');
        }
        if (!$this->_iv) {
            throw new Exception('Aes encrypt failed, iv not found!');
        }
    }

    public function encode($data) {
        $data = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->_key, $data, MCRYPT_MODE_CBC, $this->_iv));
        $data = str_replace(array('+'),array('%2B'), $data);
        return $data;
    }

    public function decode($data) {
        $data = str_replace(array('%2B'),array('+'), $data);
        $data = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->_key, base64_decode($data), MCRYPT_MODE_CBC, $this->_iv), "\0\4");
        return $data;
    }
}